package com.polaris.live.ui.message.fragment

import android.os.Bundle
import android.text.Editable
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.adapter.message.FamilyMessageAdapter
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.FragmentMainFamilyBinding
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.manager.UserStateManager
import com.polaris.live.resp.back_resp.AgencyMemberIndicatorResp
import com.polaris.live.translation.R.string
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.state.copyState
import com.polaris.live.utils.state.getDisplayPosition
import com.polaris.live.viewmodel.message.FamilyMessageViewModel
import com.polaris.live.widget.refresh.ListOperator

/**
 * MainFamilyFragment 主页家族
 *
 * @author Created by 半仙 on 2024/6/27/027 9:47
 */
class MainFamilyFragment : BaseVbFragment<FamilyMessageViewModel, FragmentMainFamilyBinding>(), OnAutoRefreshListener {

    private val mAdapter by lazy { FamilyMessageAdapter() }
    private var mListOperator: ListOperator<AgencyMemberIndicatorResp>? = null

    private var mTotalBack: ((total: Long) -> Unit)? = null
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.tvSearch.alpha = 0.4f
        mBinding.reRecycler.setEmptyTip(R.drawable.family_empty, "")
        mBinding.reRecycler.apply {
            recycler.adapter = mAdapter
            recycler.layoutManager = LinearLayoutManager(requireContext())
            mListOperator = attachedAdapter(mAdapter, mViewModel)
            mListOperator?.observe(this@MainFamilyFragment, mViewModel.mAgencyLiveData)
        }
        initObserver()
        initListener()

    }

    private fun initListener() {
        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.data[position]
            Router.instance.setPath(RoutePath.MESSAGE_ACTIVITY)
                .withInt("page", UserConst.From.UNKNOWN)
                .withString("nickname", item.memberUser.nickname)
                .withString("avatar", item.memberUser.avatar)
                .apply {
                    item.memberUser.avatarFrame?.also { af ->
                        withString("avatarFrame", af)
                    }
                    item.memberUser.chatBubble?.also { cb ->
                        withString("chatBubble", cb)
                    }
                }
                .withLong("userId", item.memberUser.userId)
                .navigation()
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.data[position]

            when (view.id) {
                R.id.goto_room -> {
                    when (item.memberUser.liveType) {
                        //派对房VIDEO_PARTY派对房
                        LiveConst.Type.PARTY_LIVE, LiveConst.Type.VIDEO_PARTY -> {
                            Router.instance.setPath(RoutePath.PARTY_SPECTATOR_ACTIVITY)
                                .withInt(LiveConst.Params.LIVETYPE, item.memberUser.liveType)
                                .withLong(LiveConst.Params.ANCHORID, item.memberUser.userId)
                                .navigation(context)
                        }
                        //游戏房
                        LiveConst.Type.PARTY_GAME_LIVE -> {
                            Router.instance.setPath(RoutePath.PARTY_GAME_SPECTATOR_ACTIVITY)
                                .withLong(LiveConst.Params.ANCHORID, item.memberUser.userId)
                                .navigation(context)
                        }
                        //仅直播，直播坐等
                        LiveConst.Type.ONLY_LIVE, LiveConst.Type.LIVE_AND_MATCH -> {
                            LiveUtils.toSpectator(item.memberUser.userId).navigation(requireContext())
                        }
                    }

                }

                R.id.cons_head -> {
                    Router.instance.setPath(RoutePath.USER_SPACE_ACTIVITY)
                        .withInt("page", UserConst.From.UNKNOWN)
                        .withAny("userBasic", item.memberUser)
                        .withLong("userId", item.memberUser.userId).navigation()
                }
            }


        }
        mBinding.editClear.setOnSingleClickListener {
            mBinding.searchEdit.setText("")
        }
        mBinding.tvSearch.setOnSingleClickListener {
            val searchString = mBinding.searchEdit.text.toString()
            if (searchString.isNotEmpty()) {
                mListOperator?.resetData()
                mViewModel.searchAgency(searchString)
            } else {
                ToastGravity.showGravity(StringUtils.getString(string.please_input_context))
            }
        }
        mBinding.searchEdit.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                val searchString = mBinding.searchEdit.text.toString()
                if (searchString.isEmpty()) {
                    mBinding.apply {
                        tvSearch.alpha = 0.4f
                        peopleImg.setImageResource(R.drawable.family_people_1)
                        editClear.setImageResource(R.drawable.family_clear_1)
                        editClear.visibility = View.GONE
                    }
                    mListOperator?.resetData()
                    mViewModel.searchAgency(null)
                } else {
                    mBinding.apply {
                        tvSearch.alpha = 1f
                        peopleImg.setImageResource(R.drawable.family_people_2)
                        editClear.setImageResource(R.drawable.family_clear_2)
                        editClear.visibility = View.VISIBLE
                    }

                }
            }
        })
    }

    private fun initObserver() {
        mViewModel.mAgencyLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mTotalBack?.invoke(it.total)
            })
        }
        //监听当前列表用户状态
        UserStateManager.observe(this, {
            getDisplayUserIds()
        }, { messages ->
            val indices = mBinding.reRecycler.recycler.getDisplayPosition(mAdapter.data)?.indices
                ?: mAdapter.data.indices

            messages.forEach { message ->
                for (i in indices) {
                    val item = mAdapter.getItem(i).memberUser
                    if (item.userId == message.state.userId) {
                        val newBean = mAdapter.data[i].let {
                            it.copy(memberUser = it.memberUser.copyState(message))
                        }
                        mAdapter.setData(i, newBean)
                        break
                    }
                }
            }
        })

        mBinding.reRecycler.recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    updateUserStateObserve()
                }
            }
        })
    }

    private fun updateUserStateObserve(userIds: List<Long> = getDisplayUserIds()) {
        UserStateManager.updateUserObserve(this, userIds)
    }

    private fun getDisplayUserIds(): List<Long> {
        val wrapper = mAdapter.recyclerView.getDisplayPosition(mAdapter.data)
            ?: return emptyList()

        return mAdapter.data.subList(wrapper.firstPosition, wrapper.lastPosition).mapNotNull {
            it.memberUser.userId
        }
    }

    override fun onAutoRefresh() {
        mViewModel.onRefresh()
    }


    fun setTotalBack(totalBack: (total: Long) -> Unit) {
        mTotalBack = totalBack
    }
}